package com.neulogistics.contrib.warehouse.api.application.integrationevent.handler;

import com.blackto.lib.eventbus.abstraction.IIntegrationEventHandler;
import com.neulogistics.contrib.warehouse.api.application.integrationevent.subscribe.GoodsCreatedIntegrationEvent;
import com.neulogistics.contrib.warehouse.api.application.query.IWarehouseQueryService;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.po.InventoryPO;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.service.IInventoryPOService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Component
public class GoodsCreatedIntegrationEventHandler implements IIntegrationEventHandler<GoodsCreatedIntegrationEvent> {
    @Resource
    IWarehouseQueryService warehouseQueryService;

    @Resource
    IInventoryPOService inventoryPOService;

    @Override
    public CompletableFuture<Void> handle(GoodsCreatedIntegrationEvent event) {
        // 获取所有库房id，更新库存目录
        List<Integer> ids = warehouseQueryService.getAllWarehouseId();

        List<InventoryPO> inventoryPOSToSave = ids.stream().map(warehouseId -> {
            return new InventoryPO(warehouseId, event.goodsId, event.goodsName, event.measureUnit);
        }).collect(Collectors.toList());

        inventoryPOService.saveBatch(inventoryPOSToSave);

        return CompletableFuture.completedFuture(null);
    }
}
